/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package view;

import GUI.JFrameBase;
import java.io.File;
import java.sql.Time;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreePath;
import libraries.Application;
import libraries.FileLibrary;
import libraries.FileLibrary.MyException;
import libraries.FunctionLibrary;
import model.DB2Hash;

/**
 *
 * @author aeguzkiza
 */
public class AcquisitionPanelView {
    // Text by default
    private String fieldNames = "\n- Ojo bajo estudio \n- Ruta de la imagen \n- Debe existir una imagen cargada \n- Pérdidas de fijación \n- Foveal"
            + "\n- Errores de falsos positivos \n- Errores de falsos negativos \n- Duración de la prueba"
            + "\n- Prueba de Hemicampo en Glaucoma (PHG) \n- Desviación Media (DM) \n- Desviación Estándar del Patrón (DSM)";

    private String wrongFixation = "El valor de fijación es incorrecto. \nLas pérdidas de fijación obtenidas no pueden superar el número de comprobaciones de las mismas.";


    // Initialize variables
    public boolean isNew;
    private final JFrameBase frame;
    private FunctionLibrary LF = new FunctionLibrary();
    private FileLibrary FLib = new FileLibrary();

    public AcquisitionPanelView(JFrameBase frame) {
        this.frame = frame;
    }
    public void updateAcquisitionData(DB2Hash a) {
        this.isNew = false;
        
        // Acquisition name:
        frame.AcquisitionNameInput.setText(a.get("AcquisitionName"));

        // Selected eye:
            if(a.get("ImageLaterality").toUpperCase().equals("L")){
                frame.LeftEyeRadioButton.setSelected(true);
            }else if(a.get("ImageLaterality").toUpperCase().equals("R")){
                frame.RightEyeRadioButton.setSelected(true);
            }else{
                frame.EyeButtonGroup.clearSelection();
            }
        
        // Reliability factors:
            frame.FixationLossesCheckedInput.setText(a.get("FixationCheckedQuantity"));
            frame.FixationLossesInput.setText(a.get("PatientNotProperlyFixatedQuantity"));
            
            if(a.get("FovealSensitivityMeasured").toUpperCase().equals("YES")){
                frame.FovealRadioButton1.setSelected(true);
                frame.SensibilityInput.setText(a.get("FovealSensitivity"));
            }else if(a.get("FovealSensitivityMeasured").toUpperCase().equals("NO")){
                frame.FovealRadioButton2.setSelected(true);
                frame.SensibilityInput.setText("");
            }else{
                frame.FovealRadioButton1.setSelected(frame.defaultFoveal);
                frame.FovealRadioButton2.setSelected(!frame.defaultFoveal);
                frame.SensibilityInput.setText("");
            }
            
            frame.FalsePositivesInput.setText(a.get("FalsePositivesEstimate"));
            frame.FalseNegativesInput.setText(a.get("FalseNegativesEstimate"));
            
            String VisualFieldTestDuration = a.get("VisualFieldTestDuration");
            if(VisualFieldTestDuration.length() != 0){
                String[] VisualFieldTestDuration_Splitted = VisualFieldTestDuration.split(":");
                frame.TestDurationInput1.setText(VisualFieldTestDuration_Splitted[1]);
                frame.TestDurationInput2.setText(VisualFieldTestDuration_Splitted[2]);

            }else{
                frame.TestDurationInput1.setText(null);
                frame.TestDurationInput2.setText(null);
            }
            
        // Image preview
            frame.ImagePathInput.setText(a.get("ImagePath"));
            File file = new File(a.get("ImagePath"));
            frame.loadImage(file);

        // Global rates:
            String GlobalIndexName = a.get("GlobalIndexName");
            if(GlobalIndexName.isEmpty()){GlobalIndexName = frame.defaultGlobalIndexName;}
            frame.GlobalIndexNameComboBox.setSelectedItem(GlobalIndexName);
            // GHT (Glaucoma Hemifield Test)
            String GlaucomaHemifieldTestAnalysisCodeSequence = a.get("GlaucomaHemifieldTestAnalysisCodeSequence");
            if(GlaucomaHemifieldTestAnalysisCodeSequence.isEmpty()){GlaucomaHemifieldTestAnalysisCodeSequence = frame.defaultPHG;}
            frame.PHGComboBox.setSelectedItem(GlaucomaHemifieldTestAnalysisCodeSequence);

            // DM
            frame.DMInput1.setText(a.get("GlobalDeviationFromNormal"));

            if(a.get("GlobalDeviationProbabilityNormalsExist").toUpperCase().equals("YES")){
                frame.DMCheckBox.setSelected(true);                             // There's a value.
                frame.DMInput2.setText(a.get("GlobalDeviationProbability"));    // Writes that value.
            }else if(a.get("GlobalDeviationProbabilityNormalsExist").toUpperCase().equals("NO")){
                frame.DMCheckBox.setSelected(false);
                frame.DMInput2.setText("");
            }else{
                frame.DMCheckBox.setSelected(frame.defaultDM);
                frame.DMInput2.setText("");
            }

            // DSM
            frame.DSMInput1.setText(a.get("LocalizedDeviationFromNormal"));
            if(a.get("LocalDeviationProbabilityNormalsExist").toUpperCase().equals("YES")){
                frame.DSMCheckBox.setSelected(true);                            // There's a value.
                frame.DSMInput2.setText(a.get("LocalizedDeviationProbability"));    // Writes that value.
            }else if(a.get("LocalDeviationProbabilityNormalsExist").toUpperCase().equals("NO")){
                frame.DSMCheckBox.setSelected(false);
                frame.DSMInput2.setText("");
            }else{
                frame.DSMCheckBox.setSelected(frame.defaultDSM);
                frame.DSMInput2.setText("");
            }

            // SF
            if(a.get("ShortTermFluctuationCalculated").toUpperCase().equals("YES")){
                frame.SFCheckBox.setSelected(true);                     // There's a value.
                frame.SFInput1.setText(a.get("ShortTermFluctuation"));  // Writes that value.
            }else if(a.get("ShortTermFluctuationCalculated").toUpperCase().equals("NO")){
                frame.SFCheckBox.setSelected(false);
                frame.SFInput1.setText("");
            }else{
                frame.SFCheckBox.setSelected(frame.defaultSF);
                frame.SFInput1.setText("");
            }

            // CPSD
            if(a.get("CorrectedLocalizedDeviationFromNormalCalculated").toUpperCase().equals("YES")){
                frame.CPSDCheckBox.setSelected(true);                                       // There's a value.
                frame.CPSDInput1.setText(a.get("CorrectedLocalizedDeviationFromNormal"));   // Writes that value.
            }else if(a.get("CorrectedLocalizedDeviationFromNormalCalculated").toUpperCase().equals("NO")){
                frame.CPSDCheckBox.setSelected(false);
                frame.CPSDInput1.setText("");
            }else{
                frame.CPSDCheckBox.setSelected(frame.defaultCPSD);
                frame.CPSDInput1.setText("");
            }
                
        
    }
    public DB2Hash getAcquisitionData(ArrayList<String> keys, Integer StudyId) throws MyException {
        System.out.println("START OF Get Acquisition Data");
        this.isNew = false;
        DB2Hash acquisition = new DB2Hash();
        // Start collecting data
        String Id = null;
        int Sent = 0;       // If an acquisition is recently created, it coludn't be already sent.
        
        
        
        // Acquisition capture
        String ImageLaterality = "";
        if(frame.LeftEyeRadioButton.isSelected()){ImageLaterality= "L";
        }else if(frame.RightEyeRadioButton.isSelected()){ImageLaterality= "R";}

        String AcquisitionTime = null;
        String AcquisitionName = frame.AcquisitionNameInput.getText();        
        if(AcquisitionName.isEmpty()){    // StudyName is edited only once.
            // Get current acquisition time.
            AcquisitionTime = frame.parseTime(null);  // Get current time from the system clock.
            //System.out.println("AcquisitionTime: "+AcquisitionTime);
            // Eye traslation:
            String eye = LF.eyeTranslation(ImageLaterality);

            // UID = DICOMprefix + StudyDate + random number.
            this.isNew = true;
            Random randomGenerator = new Random();
            String random = Integer.toString(randomGenerator.nextInt(frame.randomMargin));
            AcquisitionName = eye+AcquisitionTime+random;
            AcquisitionName = AcquisitionName.replaceAll(":", "");
            //frame.StudyNameInput.setText(StudyName);    // Don't write study UID until study had been saved into database.
            System.out.println("Generated random Name: "+AcquisitionName);
        }else{  // Mantains time values on old acquisitions.
            /*TreePath path = frame.getTreePath();
            DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode) path.getLastPathComponent();
            int nodeLevel = selectedNode.getLevel();
            if(nodeLevel == 3){
                view.Acquisition z = (view.Acquisition)selectedNode.getUserObject();
                AcquisitionTime = z.getTime();
            }*/
            view.Acquisition z = frame.z;   // Get the currently selected acquisition node.   
            AcquisitionTime = z.getTime();
        }

        // Image variables
        String ImagePath = frame.ImagePathInput.getText();
        ImageIcon image = (ImageIcon) frame.ImagePreviewLabel.getIcon(); 
        int imageHeight = image.getIconHeight();
        //System.out.println("imageHeight: "+imageHeight);
               
        // Reliability factors
        String FixationLossesCheckedInput = frame.FixationLossesCheckedInput.getText();
        String PatientNotProperlyFixatedQuantity = frame.FixationLossesInput.getText();
        String FovealSensitivityMeasured = "";
        String FovealSensitivity = "0";
        if(frame.FovealRadioButton1.isSelected()){
            FovealSensitivityMeasured= "YES";
            FovealSensitivity = frame.SensibilityInput.getText();
        }else if(frame.FovealRadioButton2.isSelected()){
            FovealSensitivityMeasured= "NO";}
        
        String FalsePositivesEstimate = frame.FalsePositivesInput.getText();
        String FalseNegativesEstimate = frame.FalseNegativesInput.getText();

        String VisualFieldTestDuration = "00:"+frame.TestDurationInput1.getText()+":"+frame.TestDurationInput2.getText();
        
        // Global indices
        String GlobalIndexName = frame.GlobalIndexNameComboBox.getSelectedItem().toString();
        String GlaucomaHemifieldTestAnalysisCodeSequence = frame.PHGComboBox.getSelectedItem().toString();

        String GlobalDeviationFromNormal = frame.DMInput1.getText();
        String GlobalDeviationProbability = "0";
        String GlobalDeviationProbabilityNormalsExist = "NO";
        if(frame.DMCheckBox.isSelected()){
            GlobalDeviationProbabilityNormalsExist = "YES";
            GlobalDeviationProbability = frame.DMInput2.getText();
        }
                
        String LocalizedDeviationFromNormal = frame.DSMInput1.getText();
        String LocalizedDeviationProbability = "0";
        String LocalDeviationProbabilityNormalsExist = "NO";
        if(frame.DSMCheckBox.isSelected()){
            LocalDeviationProbabilityNormalsExist = "YES";
            LocalizedDeviationProbability = frame.DSMInput2.getText();
        }

        String ShortTermFluctuation = "0";
        String ShortTermFluctuationCalculated = "NO";
        if(frame.SFCheckBox.isSelected()){
            ShortTermFluctuationCalculated = "YES";
            ShortTermFluctuation = frame.SFInput1.getText();
        }

        String CorrectedLocalizedDeviationFromNormal = "0";
        String CorrectedLocalizedDeviationFromNormalCalculated = "NO";
        if(frame.CPSDCheckBox.isSelected()){
            CorrectedLocalizedDeviationFromNormalCalculated = "YES";
            CorrectedLocalizedDeviationFromNormal = frame.CPSDInput1.getText();
        }
                

        if(ImageLaterality.isEmpty() || ImagePath.isEmpty() || FixationLossesCheckedInput.isEmpty() || PatientNotProperlyFixatedQuantity.isEmpty() || FovealSensitivityMeasured.isEmpty()
           || FalsePositivesEstimate.isEmpty() || FalseNegativesEstimate.isEmpty() || VisualFieldTestDuration.equals(":")
           || GlobalIndexName.isEmpty() || GlaucomaHemifieldTestAnalysisCodeSequence.isEmpty() || GlobalDeviationFromNormal.isEmpty()
           || LocalizedDeviationFromNormal.isEmpty()){
            JOptionPane.showMessageDialog(frame.ImagePanel, this.frame.emptyField+fieldNames, frame.errorTxt,JOptionPane.ERROR_MESSAGE);
            
        }else if(Integer.parseInt(frame.FixationLossesInput.getText()) > Integer.parseInt(frame.FixationLossesCheckedInput.getText())){ // There is no image on the preview label.
            JOptionPane.showMessageDialog(frame.ImagePanel, this.wrongFixation, frame.errorTxt,JOptionPane.ERROR_MESSAGE);
        }else if(imageHeight <= 0){ // There is no image on the preview label.
            JOptionPane.showMessageDialog(frame.ImagePanel, this.frame.emptyImageLabel, frame.errorTxt,JOptionPane.ERROR_MESSAGE);
        }else{
            File file = new File(ImagePath);
            String outPath = frame.savePath + "\\" + file.getName();
            if(!ImagePath.equals(outPath)){   // Move the image to the image database folder (only for new images that are outside this folder).
                FLib.moveFile(file.getName(), file.getPath(), frame.savePath);
                ImagePath = outPath; // Saves the true image path in database.
                frame.ImagePathInput.setText(ImagePath);    // Refreshes the path to the new directory.
            }

            // Defines in order the data to insert in database (don't touch!).
            List<String> values = Arrays.asList(Id, Integer.toString(StudyId), Integer.toString(Sent), AcquisitionTime, AcquisitionName, ImageLaterality, 
            ImagePath, FixationLossesCheckedInput, PatientNotProperlyFixatedQuantity, FalseNegativesEstimate, FalsePositivesEstimate, FovealSensitivityMeasured,
            FovealSensitivity, VisualFieldTestDuration, GlobalIndexName, GlaucomaHemifieldTestAnalysisCodeSequence, GlobalDeviationFromNormal, GlobalDeviationProbabilityNormalsExist,
            GlobalDeviationProbability, LocalizedDeviationFromNormal, LocalDeviationProbabilityNormalsExist, LocalizedDeviationProbability, ShortTermFluctuationCalculated,
            ShortTermFluctuation, CorrectedLocalizedDeviationFromNormalCalculated, CorrectedLocalizedDeviationFromNormal);
            //System.out.println("Keys size:"+keys.size());
            for(int i = 1; i<keys.size();i++){  // Doesn't write Id value (i=0).
                //System.out.println("Keys: "+keys.get(i)+" Values: "+values.get(i));
                acquisition.put(keys.get(i), values.get(i));
            }

        }
        return acquisition;
     }

     public void clearAll(){
        // Clear all data.
        frame.AcquisitionNameInput.setText(null);
        frame.EyeButtonGroup.clearSelection();

        frame.FixationLossesInput.setText(null);
        frame.FovealButtonGroup.clearSelection();
        frame.SensibilityInput.setText(null);
        frame.FalsePositivesInput.setText(null);
        frame.FalseNegativesInput.setText(null);
        frame.TestDurationInput1.setText(null);
        frame.TestDurationInput2.setText(null);

        frame.ImagePathInput.setText(null);
        frame.ImagePreviewLabel.setIcon(null);

        frame.GlobalIndexNameComboBox.setSelectedIndex(0);
        frame.PHGComboBox.setSelectedIndex(0);
        frame.DMInput1.setText(null);
        frame.DMInput2.setText(null);
        frame.DMCheckBox.setSelected(false);

        frame.DSMInput1.setText(null);
        frame.DSMInput2.setText(null);
        frame.DSMCheckBox.setSelected(false);

        frame.SFInput1.setText(null);
        frame.SFCheckBox.setSelected(false);

        frame.CPSDInput1.setText(null);
        frame.CPSDCheckBox.setSelected(false);
     }

}
